<?php
/**
 * Created by PhpStorm.
 * User: 李沂君
 * Date: 2023/2/21
 * Time: 10:38
 */

namespace app\api\controller;
use app\admin\model\Index;
use app\common\controller\Api;
use think\Db;
use app\admin\model\Auth;
use think\Config;
use think\Log;
use app\admin\model\Ctrip;
use app\admin\model\Bluecop;

/**
 * 我的
 */
class Mine extends Api
{
    protected $noNeedLogin = ['tokens','tokeninfo','token','myVoucher'];
    protected $noNeedRight = ['*'];

    public function userinfo(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $no_used_num=Db::name("order")->where(['status'=>2,'user_id'=>$userInfo['id']])->count();//待使用
        $coupon=Db::name("user_coupon")->where(['status'=>1,'user_id'=>$userInfo['id']])->count();//待使用
        $orderlist = Db::name('order')->where('user_id',$userInfo['id'])->where('status','in',[4,2])->column('id');
        $voucher=Db::name("voucher")->where('order_id','in',$orderlist)->where(['voucher_status'=>'EFFECTIVE','user_id'=>$userInfo['id']])->count();//待使用
        $info=[
            'nickname'=>$userInfo['nickname'],
            'avatar'=>$userInfo['avatar'],
            'birthday'=>$userInfo['birthday'],
            'no_used_num'=>$no_used_num,
            'coupon'=>$coupon,
            'voucher'=>$voucher,
        ];
        $this->success("获取成功",$info);
    }


    /**
     * 首页
     *
     * @ApiMethod (POST)
     * @param int $token token
     */
    public function index(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        if($userInfo['vip_id']){
            $vip_name = Db::name("operator_vip")->where(['id'=>$userInfo['vip_id']])->value('vip_name');
            $vip_end_time = $userInfo['vip_end_time'];
        }else{
            $vip_name = '普通用户';
            $vip_end_time = '无';
        }
        $this->success("获取成功",[
            'nickname'=>$userInfo['nickname'],
            'avatar'=>$userInfo['avatar'],
            'birthday'=>$userInfo['birthday'],
            'gender'=>$userInfo['gender'],
            'vip_name'=>$vip_name,
            'vip_end_time'=>$vip_end_time,
        ]);
    }
    /**
     * 取消订单
     */
    public function cancellation(){
        $datainfo = Index::setDecryptArray(Config::get("miyao.shi"),input());
        $datainfo = json_decode($datainfo,true);
        $id =  $datainfo['id'];
        $order = Db::name("order")->where(['id'=>$id])->find();
        if($order['status'] == 1){
            if($order['coupon_id']>0){
                $user_coupon = Db::name("user_coupon")->where(['id'=>$order['coupon_id']])->find();
                if($user_coupon){
                    Db::name("user_coupon")->where(['id'=>$order['coupon_id']])->update(['status'=>1,'order_id'=>0]);
                }
            }
            Db::name("order")->where(['id'=>$id])->update(['status'=>3]);
        }
        $this->success("取消订单成功");
    }

    /**
     * 批量取消
     */
    public function canceorder($user_id){
        $expire = Db::query("
          select `id`
          from fa_order
          where now() >SUBDATE(createtime,interval -1 minute) AND status = 1 AND user_id = '.$user_id.';
          ");
        $order = Db::name("order")->where('id','in',$expire)->field('id,coupon_id')->select();
        foreach ($order as $v){
            Db::name("order")->where('id',$v['id'])->update(['status'=>3]);
        }
    }
    /**
     * 我的订单
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $status 状态 1、待付款 2、待使用 3、付款失败 4、已使用 5、退款中/已完成退款
     * @param int $type 类型 1阿里 2自建 3携程 4优惠券 5小蓝券 6恩拉直充 7恩拉卡密 8橙券直充 9橙券卡密 10联联 11爱吃星球
     * @param int $page 页码
     * @param int $page_size 每页条数
     */
    public function myOrderList(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $this->canceorder($user_id);
        $page = input('page',1);
        $page_size = input('page_size',10);
        $status = input('status',0);
        $type = input('type',0);
        $map['user_id'] = $userInfo['id'];
        if($status){
            $map['status'] = $status;
        }
        if($type){
            $map['type'] = $type;
        }
        $order = Db::name("order")->where($map)->order(['createtime'=>'desc'])->page($page,$page_size)->select();
        foreach ($order as &$v){
            if($v['type'] == 1){
                $v['voucher_id']=Db::name('voucher')->where('biz_order_id',$v['biz_order_id'])->value('id');
            }else{
                $v['voucher_id']=Db::name('voucher')->where('order_id',$v['id'])->value('id');
            }
        }
        $count = Db::name("order")->where($map)->count();
        $this->success("获取成功",[
            'list'=>$order,
            'count'=>$count
        ]);
    }

    /**
     * 订单详情
     * @ApiMethod (POST)
     * @param int $token 订单的token
     * @param int $id 订单的id
     */
    public function orderInfo(){
        $map['id'] = input('id');
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $map['user_id'] = $userInfo['id'];
        $data = Db::name("order")->where($map)->find();
        if(!empty($data)){
            if($data['type'] == 1){
                $data['voucher_id'] = Db::name('voucher')->where('biz_order_id',$data['biz_order_id'])->value('id');
            }else{
                $data['voucher_id'] = Db::name('voucher')->where('order_id',$data['id'])->value('id');
            }
            $data['createtime'] = strtotime($data['createtime']);
        }
        $this->success("获取成功",$data);
    }

    /**
     * 凭证
     */
    public function orderpz(){
        $map['order_id'] = input('id');
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $map['user_id'] = $userInfo['id'];
        $order = Db::name('order')->where('id',$map['order_id'])->where('status','in',[4,2])->find();
        if($order){
            $data = Db::name("voucher")->where($map)->field('id,item_id,title,expire_time,ticket_code,order_amount,voucher_status,ProductUseMsg')->find();
        }else{
            $data = '';
        }
        $this->success("获取成功",$data);
    }



    /**
     * 我的优惠券
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $page 页码
     * @param int $page_size 每页条数
     * @param int $status 状态1、待使用 2、已使用 3、已过期
     */
    public function myCoupon(){
//        Index::checkCoupon();//优惠券过期自动检测
        $page = input('page',1);
        $page_size = input('page_size',20);
        $status = input('status',0);
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $map['a.user_id'] = $userInfo['id'];
        if($status){
            $map['a.status'] = $status;
        }
        $data = Db::name("user_coupon")
            ->alias('a')
            ->join('coupon b','b.id = a.coupon_id','left')
            ->field(['a.id','b.title','a.amount','a.status','b.rule','a.createtime','a.expire_time'])
            ->where($map)
            ->page($page,$page_size)
            ->order(['createtime'=>'desc'])
            ->select();
        $count = Db::name("user_coupon")->alias('a')->where($map)->count();

        $keyong = Db::name('user_coupon')->where('user_id',$userInfo['id'])->where('status',1)->count();
        $bukeyong = Db::name('user_coupon')->where('user_id',$userInfo['id'])->where('status',3)->count();
        $this->success("获取成功",[
            'list'=>$data,
            'count'=>$count,
            'keyong'=>$keyong,
            'bukeyong'=>$bukeyong,
        ]);
    }

    /**
     * 投诉建议
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $name 联系人
     * @param int $mobile 联系电话
     * @param int $images 相关图片
     * @param int $content 投诉内容
     */
    public function feeback(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $name = input("name");
        $mobile = input("mobile");
        $images = input("images");
        $content = input("content");
        if(empty($name)||empty($mobile)||empty($images)||empty($content)){
            $this->error("请将表单填写完整");
        }else{
            Db::name("feeback")->insert([
                'user_id'=>$userInfo['id'],
                'name'=>$name,
                'mobile'=>$mobile,
                'images'=>$images,
                'content'=>$content,
                'createtime'=>time()
            ]);
            $this->success("感谢反馈,后台已收到~！");
        }
    }


    /**
     * 获取个人信息
     *
     * @ApiMethod (POST)
     * @param int $token token
     */
    public function getUserInfo(){
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $this->success("获取成功",[
            'avatar'=>$userInfo['avatar'],
            'nickname'=>$userInfo['nickname'],
            'gender'=>$userInfo['gender'],
            'birthday'=>$userInfo['birthday'],
            'vip_id'=>$userInfo['vip_id'],
        ]);
    }

    /**
     * 编辑个人信息
     *
     * @ApiMethod (POST)
     * @param sting $token token
     * @param string $avatar 头像
     * @param string $nickname 昵称
     * @param string $gender 性别 0、未知 1、男 2、女
     * @param string $birthday 出生日期
     *
     */
    public function updateInfo(){
        $nickname = input("nickname");
        $avatar = input("avatar");
        $gender = input("gender");
        $birthday = input("birthday");
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        if(empty($nickname)||empty($avatar)||empty($gender)||empty($birthday)){
            $this->error("请将表单填写完整");
        }else{
            Log::record("修改获取到的参数:".json_encode(input()),'info');
            Db::name("user")->where(['id'=>$userInfo['id']])->update([
                'nickname'=>$nickname,
                'avatar'=>$avatar,
                'gender'=>$gender,
                'birthday'=>$birthday
            ]);
            $this->success("修改成功");
        }
    }

    /**
     * 我的券码
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $page 页码
     * @param int $page_size 每页条数
     * @param int $biz_order_id 淘宝子订单号[非必填]
     * @param string $status 券码状态[可用EFFECTIVE、已用USED、失效CANCELED]
     */
    public function myVoucher(){
        $user_id = $this->auth->id;;
        $userInfo = Auth::userInfo($user_id);
        $stauts = input("status",0);
        $page = input('page',1);
        $page_size = input('page_size',20);
        $map['user_id'] = $userInfo['id'];
        if($stauts){
            $map['voucher_status'] = $stauts;
        }
        $orderlist = Db::name('order')->where('user_id',$userInfo['id'])->where('status','in',[4,2])->column('id');
        $data = Db::name("voucher")->where($map)
            ->where('order_id','in',$orderlist)
            ->page($page,$page_size)
            ->order(['id'=>'desc'])->select();
        foreach ($data as &$v){
            if(empty($v['order_id'])){
                $v['order_info'] =  Db::name('order')->where('biz_order_id',$v['biz_order_id'])->field('main_picture,title,order_no')->find();
            }else{
                $v['order_info'] = Db::name('order')->where('id',$v['order_id'])->field('main_picture,title,order_no')->find();
            }
        }
        $count = Db::name("voucher") ->where('order_id','in',$orderlist)->where($map)->count();
        $this->success("获取成功",[
            'list'=>$data,
            'count'=>$count
        ]);

    }


    /**
     * 生成凭证接口
     */
    public function coupz(){
        $order_id =input('id');
        $order =  Db::name('order')->where('id',$order_id)->find();
        $voucher = $this->voucher($order['outer_order_id']);
        if($voucher['ResultStatus']['IsSuccess'] === true){
            if(isset($voucher['VoucherOrderItemInfoList'][0]['VoucherWrapInfoList'][0]['VoucherNO'])){
                $ticket_code = $voucher['VoucherOrderItemInfoList'][0]['VoucherWrapInfoList'][0]['VoucherNO'];
            }else{
                $ticket_code = $order['order_no'];
            }
            if(isset($voucher['VoucherOrderItemInfoList'][0]['ProductUseMsg'])){
                $ProductUseMsg = $voucher['VoucherOrderItemInfoList'][0]['ProductUseMsg'];
            }else{
                $ProductUseMsg = '';
            }
            if(isset($voucher['VoucherOrderItemInfoList'][0]['VendorVoucher'])){
                $VendorVoucher = $voucher['VoucherOrderItemInfoList'][0]['VendorVoucher'];
            }else{
                $VendorVoucher = '';
            }
            if(isset($voucher['VoucherOrderItemInfoList'][0]['ResourceName'])){
                $ResourceName = $voucher['VoucherOrderItemInfoList'][0]['ResourceName'];
            }else{
                $ResourceName = '';
            }

            Db::name('voucher')->insert([
                'item_id'=>makeOrderNum(),
                'voucher_id'=>$order['resource_id'],
                'effect_time'=>$order['createtime'],
                'expire_time'=>$order['time'],
                'title'=>$ResourceName,
                'ProductUseMsg'=>$ProductUseMsg,
                'VendorVoucher'=>$VendorVoucher,
                'ticket_code'=>$ticket_code,
                'type'=>3,
                'user_id'=>$order['user_id'],
                'order_id'=>$order['id'],
                'order_amount'=>$order['amount'],
            ]);
        }else{
            Db::name('voucher')->insert([
                'item_id'=>makeOrderNum(),
                'voucher_id'=>$order['resource_id'],
                'effect_time'=>$order['createtime'],
                'expire_time'=>$order['time'],
                'type'=>3,
                'user_id'=>$order['user_id'],
                'order_id'=>$order['id'],
                'order_amount'=>$order['amount'],
            ]);
        }
        $this->success('生成凭证成功');
    }


    /**
     * 我的券码携程
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $id 券码的id
     */
    public function voucherInfoCx(){
        $id = input('id');
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $map['user_id'] = $userInfo['id'];
        $map['id'] = $id;
        $info = Db::name("voucher")->where($map)->find();
        if($info['ProductUseMsg'] == ''||$info['ProductUseMsg'] == null ) {
            $order = Db::name('order')->where('id', $info['order_id'])->find();
            $voucher = $this->voucher($order['outer_order_id']);
            if ($voucher['ResultStatus']['IsSuccess'] === true) {
                if (isset($voucher['VoucherOrderItemInfoList'][0]['VoucherWrapInfoList'][0]['VoucherNO'])) {
                    $ticket_code = $voucher['VoucherOrderItemInfoList'][0]['VoucherWrapInfoList'][0]['VoucherNO'];
                } else {
                    $ticket_code = $order['order_no'];
                }
                if (isset($voucher['VoucherOrderItemInfoList'][0]['ProductUseMsg'])) {
                    $ProductUseMsg = $voucher['VoucherOrderItemInfoList'][0]['ProductUseMsg'];
                } else {
                    $ProductUseMsg = '';
                }
                if (isset($voucher['VoucherOrderItemInfoList'][0]['VendorVoucher'])) {
                    $VendorVoucher = $voucher['VoucherOrderItemInfoList'][0]['VendorVoucher'];
                } else {
                    $VendorVoucher = '';
                }
                if(isset($voucher['VoucherOrderItemInfoList'][0]['ResourceName'])){
                    $ResourceName = $voucher['VoucherOrderItemInfoList'][0]['ResourceName'];
                }else{
                    $ResourceName = '';
                }
                Db::name('voucher')->where('id',$info['id'])->update([
                    'title'=>$ResourceName,
                    'ProductUseMsg'=>$ProductUseMsg,
                    'VendorVoucher'=>$VendorVoucher,
                    'ticket_code'=>$ticket_code,
                ]);
            }
            $info = Db::name("voucher")->where($map)->find();
        }
        $info['order_no'] = Db::name('order')->where('id',$info['order_id'])->value('order_no');
        $refund = Db::name("resources_ctrip")->where(['resouceid'=>$info['voucher_id']])->select();
        $data=[];
        foreach ($refund as $v){
           $ctrip =  Db::name("ctrip")->where('scenicspotid',$v['scenicspotid'])->field('name,address,longitude,latitude')->find();
           $data[] = $ctrip;
        }
        $info['refundList'] = $data;
        $this->success("获取成功",$info);
    }

    public function voucher($xcid){
        $res = Ctrip::send('huoqumenpiaopinzheng',[
            'OrderId'=>$xcid,
            'SID'=>Config::get("ctrip.sid"),
            'VersionNO'=>'1.0',
            'AllianceID'=>Config::get("ctrip.aid")
        ]);
        return $res;
    }
    /**
     * 我的券码
     *
     * @ApiMethod (POST)
     * @param int $token token
     * @param int $id 券码的id
     */
    public function voucherInfo(){
        $id = input('id',0);
        $user_id = $this->auth->id;
        $userInfo = Auth::userInfo($user_id);
        $map['user_id'] = $userInfo['id'];
        $map['id'] = $id;
        $info = Db::name("voucher")->where($map)->find();
        if($info['type'] == 1 ){
            $order= Db::name('order')->where('biz_order_id',$info['biz_order_id'])->field('id,order_no')->find();
        }else{
            $order= Db::name('order')->where('id',$info['order_id'])->field('id,order_no')->find();
        }
        $info['order_no'] = $order['order_no'];
        $info['order_id'] = $order['id'];
        $this->success("获取成功",$info);
    }

    /**
     * 商品规则
     */
    public function rule(){
        $type= input('type',1);
        if($type == 1){
            $pez =  Db::name('peiz')->where('id',1)->find();
        }else if($type == 2){
            $pez =   Db::name('peiz')->where('id',2)->find();
        }
        $this->success("获取成功",$pez);
    }

}